<template>
  <div>
    <Modal
      v-model="showModal"
      :title="data ? '编辑版本' : '新建版本'"
      :styles="styles.modalStyle"
      :mask-closable="false"
      scrollable
      class="edit-container"
      @on-visible-change="close"
    >
      <vue-scroll class="form-scroll" :ops="scrollOptions" :style="styles.scrollStyle">
        <Steps :current="currentStep" class="mb30">
          <Step v-for="item in steps" :key="item" :title="item"></Step>
        </Steps>
        <Form v-show="currentStep == 0" ref="form" :model="form" :label-width="labelWidth" :rules="formRule" class="form-container">
          <Row>
            <FormItem label="版本号：" prop="VersionName">
              <SearchInput v-if="!data" :content.sync="form.VersionName" placeholder="" button="选择版本" :readonly="true" @click-btn="toChoose()" />
              <Input v-if="data" v-model="form.VersionName" readonly />
            </FormItem>
          </Row>
          <Row>
            <FormItem label="版本说明：">
              <Input v-model="form.Remark" type="textarea" :rows="5" :maxlength="MAX_REMARK"/>
            </FormItem>
          </Row>
          <Row class="radio-group">
            <FormItem label="版本状态：">
              <RadioGroup v-model="form.Enable">
                <Radio v-for="item in statusList" :key="item.Key" :label="item.Key">{{item.Value}}</Radio>
              </RadioGroup>
            </FormItem>
          </Row>
        </Form>
        <div v-show="currentStep == 1">
          <Form :label-width="60">
            <FormItem class="relative" label="SQL脚本：">
              <Upload action="x" :before-upload="beforeUpload">
                <Button type="primary" icon="ios-cloud-upload-outline">上传</Button>
              </Upload>
              <div class="tip">注：仅支持 *.sql 格式文件</div>
            </FormItem>
          </Form>
          <Table
            ref="table"
            stripe
            :data="page.list"
            :columns="columns"
            :loading="submitting"
            class="visible-table"
          />
        </div>
      </vue-scroll>
      <div slot="footer">
        <div class="footer-btn-container">
          <Button v-show="currentStep > 0" :loading="submitting" type="primary" @click="changeStep(-1)">上一步</Button>
          <Button v-show="currentStep < steps.length - 1" :loading="submitting" type="primary" @click="changeStep(1)">下一步</Button>
          <Button v-show="currentStep == steps.length - 1" :loading="submitting" type="primary" @click="submit">保存</Button>
          <Button :loading="submitting" @click="close">取消</Button>
        </div>
      </div>
    </Modal>
    <div v-if="showVersionListModal">
      <VersionList :show.sync="showVersionListModal" :content.sync="form.VersionName" />
    </div>
    <div v-if="showContentModal">
      <ContentModal :show.sync="showContentModal" title="SQL内容" :content="content" />
    </div>
  </div>
</template>

<script>
import uuid from 'uuid'

export default {
  props: {
    data: {
      type: Object
    }
  },
  data () {
    let that = this
    let Validator = this.formRuleValidator.Validator
    let statusList = [
      {
        Key: 1,
        Value: '有效'
      },
      {
        Key: 2,
        Value: '停用'
      }
    ]

    return {
      styles: this.util.getModalStyle(730, 500),
      showModal: true,
      showVersionListModal: false,
      showContentModal: false,
      labelWidth: 60,
      form: {
        VersionName: '',
        Remark: '',
        Enable: statusList[0].Key,
        SqlScripts: []
      },
      formRule: {
        VersionName: Validator.getRequiredRule(true, '必填项', 'change')
      },
      statusList,
      columns: [
        {
          title: '文件名',
          render (h, param) {
            let path = param.row.path
            const arr = path.split('/')
            return h('span', arr[arr.length - 1])
          }
        },
        {
          title: '操作',
          width: 130,
          align: 'center',
          render (h, param) {
            let row = param.row
            return h('CDropdown', {
              props: {
                button: {},
                data: row,
                list: [
                  {
                    name: uuid(),
                    button: true,
                    size: 'small',
                    text: '查看',
                    callback () {
                      that.previewItem(row)
                    }
                  },
                  {
                    name: uuid(),
                    button: true,
                    size: 'small',
                    type: 'error',
                    text: '删除',
                    callback () {
                      that.page.list.splice(param.index, 1)
                    }
                  }
                ]
              }
            })
          }
        }
      ],
      page: {
        list: []
      },
      submittingFile: false,
      MAX_REMARK: 1000,
      submitting: false,
      currentStep: 0,
      steps: ['版本信息', 'SQL脚本'],
      content: ''
    }
  },
  beforeMount () {
    if (this.data) {
      this.getById()
    }
  },
  methods: {
    close () {
      this.$emit('update:show', false)
    },
    toChoose () {
      this.showVersionListModal = true
    },
    changeStep (value) {
      // 下一步
      if (value === 1) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.currentStep += value
          }
        })
      } else {
        this.currentStep += value
      }
    },
    getById () {
      this.submitting = true
      api.getVersionPublishById({
        Id: this.data.Id
      }).then(res => {
        this.form = this.util.translateData(this.form, res.Data)
        this.page.list = this.form.SqlScripts.map(path => {
          return {
            path
          }
        })
      }).finally(() => {
        this.submitting = false
      })
    },
    beforeUpload (file) {
      let name = file.name
      const format = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
      if (format !== 'sql') {
        this.tipUtil.warning('请上传SQL文件')
      }

      let form = new FormData()
      form.append('File', file)
      this.submittingFile = true
      api.uploadVersionSql(form).then(res => {
        this.tipUtil.success('上传成功')
        this.page.list.push({
          path: res.Data
        })
      }).finally(() => {
        this.submittingFile = false
      })
      return false
    },
    previewItem (item) {
      this.submitting = true
      api.getFileContent({
        FilePath: item.path
      }).then(res => {
        this.content = res.Data || ''
        this.showContentModal = true
      }).finally(() => {
        this.submitting = false
      })
    },
    submit () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let form = this.objectUtil.copyObject(this.form)

          let arr = []
          this.page.list.forEach(item => {
            arr.push(item.path)
          })
          form.SqlScripts = arr

          let fn
          if (this.data) {
            fn = api.editVersionPublish
            form.Id = this.data.Id
          } else {
            fn = api.addVersionPublish
          }

          this.submitting = true
          fn(form).then(res => {
            this.tipUtil.success('操作成功')
            this.$emit('ok')
            this.close()
          }).catch(() => {
            this.submitting = false
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.edit-container {
  .form-container {
    .tip-msg {
      padding-left: 96px;
      color: #ccc;
    }
  }
  .tip {
    position: absolute;
    top: 1px;
    left: 100px;
  }
}
</style>
